package com.easygem.front.service.imp;

import com.easygem.common.model.front.ResourceInfo;
import com.easygem.common.model.system.SysInformation;
import com.easygem.common.response.ActiveUser;
import com.easygem.common.utils.DepUtils;
import com.easygem.common.vo.front.ResourceInfoVO;
import com.easygem.common.vo.system.PageVO;
import com.easygem.front.mapper.DepartmentMapper;
import com.easygem.front.mapper.ResourceInfoMapper;
import com.easygem.front.mapper.SysInformationMapper;
import com.easygem.front.service.ResourceInfoService;
import com.easygem.front.service.base.AbstractServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author 何维佳
 * @version 1.0
 * @className ResourceInfoServiceImpl
 * @Description TODO
 * @date 2024/12/23 18:14
 */
@Service
public class ResourceInfoServiceImpl extends AbstractServiceImpl<ResourceInfoMapper, ResourceInfo, Integer> implements ResourceInfoService {

    @Autowired
    private ResourceInfoMapper resourceInfoMapper;
    @Autowired
    private ResourceInfoService resourceInfoService;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private SysInformationMapper sysInformationMapper;

    /**
     * 多条件联表查询resource表并分页
     * @param pageNum
     * @param pageSize
     * @param resourceInfoVO
     * @return
     */
    //Integer pageNum, Integer pageSize,
    @Override
    @Async
    public PageVO<ResourceInfo> findList(Integer pageNum, Integer pageSize, ResourceInfoVO resourceInfoVO) {
        //获取当前登录用户对象
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();

//        List<Long> ids = DepUtils.getDepartmentAndChildrenIds(departmentMapper.selectAll(), activeUser.getUser().getDeptId());
//        String accountName = activeUser.getUser().getAccountName();
        PageHelper.startPage(pageNum, pageSize);
        ResourceInfo resourceInfo = new ResourceInfo();
        BeanUtils.copyProperties(resourceInfoVO, resourceInfo);
//        resourceInfo.setIds(ids);
        //设置当前登录对象的id
//        Long loginUserId = activeUser.getUser().getUserId();
//        resourceInfo.setType(activeUser.getUser().getType());
//        resourceInfo.setLoginUserId(loginUserId);
//        resourceInfo.setAccountName(accountName);
        List<ResourceInfo> resourceInfoList = resourceInfoMapper.selectResourceInfoListByResourceInfo(resourceInfo);
//        System.out.println("*************"+resourceInfoList);
        PageInfo<ResourceInfo> pageInfo = new PageInfo<>(resourceInfoList);
        return new PageVO<>(pageInfo.getTotal(), resourceInfoList);
    }

    /**
     * 根据id搜索资源信息
     * @param Id
     * @return
     */
    @Override
    public List<ResourceInfo> findListById(Long Id) {
        List<ResourceInfo> resourceInfoList = resourceInfoMapper.selectResourceInfoListById(Id);
        return resourceInfoList;
    }

    /**
     * 修改资源信息
     * @param resourceInfoVO
     * @return
     */
    @Override
    public int update(ResourceInfoVO resourceInfoVO) {
        int result = resourceInfoMapper.updateResourceInfo(resourceInfoVO);
        return result;
    }

    /**
     * 根据id删除资源信息
     * @param Id
     * @return
     */
    @Override
    public int delete(Long Id) {
        int result = resourceInfoMapper.deleteResourceInfoById(Id);
        return result;
    }

    /**
     * 添加资源进黑名单
     * @param resourceInfoVO
     * @return
     */
    @Override
    public int insertBlackList(ResourceInfoVO resourceInfoVO) {
        int isBlacklist = 1;
        int isPhonBInBlackList =1;
//        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
//        resourceInfoVO.setUserId(activeUser.getUser().getUserId());
        if (resourceInfoVO.getPhoneA()!=null && !resourceInfoVO.getPhoneA().isEmpty()) {
            isBlacklist = resourceInfoService.isBlacklist(resourceInfoVO.getPhoneA());
        }
        if(resourceInfoVO.getPhoneB()!=null && !resourceInfoVO.getPhoneB().isEmpty()) {
            isPhonBInBlackList = resourceInfoService.isBlacklist(resourceInfoVO.getPhoneB());
        }
        int resultA;
        int resultB;
        if (isBlacklist <= 0 && isPhonBInBlackList<= 0){
            resultA = resourceInfoMapper.insertBlackList(resourceInfoVO);
            resultB = resourceInfoMapper.insertBlackListB(resourceInfoVO);
            if(resultA != 0 && resultB != 0) {
                return 1;
            }
        }else if (isBlacklist <= 0) {
            //获取当前登录用户对象
            resultA = resourceInfoMapper.insertBlackList(resourceInfoVO);
            return resultA;
        }else if (isPhonBInBlackList<= 0) {
            //获取当前登录用户对象
            resultB = resourceInfoMapper.insertBlackListB(resourceInfoVO);
            return resultB;
        }
        return 0;
    }

    /**
     * 将资源转入公海
     * @param Id
     * @return
     */
    @Override
    public int insertHigh_seas_clientList(Long Id) {
        int result = resourceInfoMapper.insertHigh_seas_clientList(Id);
        return result;
    }

    /**
     * 通过多个resourceId查询resource
     * @param ids
     * @return
     */
    @Override
    public List<ResourceInfo> findAllByIds(List<Long> ids) {
//        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
//        List<Long> departmentIds = DepUtils.getDepartmentAndChildrenIds(departmentMapper.selectAll(), activeUser.getUser().getDeptId());

        ResourceInfo resourceInfo = new ResourceInfo();
//        resourceInfo.setIds(departmentIds);


        // 根据部门ID列表和resourceId列表查询客户列表
        List<ResourceInfo> resourceInfos = resourceInfoMapper.findAllByResourceId(resourceInfo, ids);
        for (ResourceInfo client : resourceInfos) {
            Integer isCall = client.getIsCall();
            String isCallStr = isCall == 0 ? "否" : (isCall == 1 ? "是" : "");
            client.setIsCallStr(isCallStr);

        }

        return resourceInfos;
    }

    /**
     * 判断资源是否在黑名单里面（内含账户名过滤）
     * @param clientPhone
     * @return
     */
    public int isBlacklist(String clientPhone) {
        //获取当前登录用户对象

//        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
//        String loginAccount_name = activeUser.getUser().getAccountName();
//        int result = resourceInfoMapper.isBlacklist(clientPhone,loginAccount_name);
        int result = resourceInfoMapper.isBlacklist(clientPhone);
        return result;
    }





    /**
     * 资源回收站
     *
     * @param pageNum        页码
     * @param pageSize       一页显示数据
     * @param resourceInfoVO 对象
     * @return
     */
    @Override
    public PageVO<ResourceInfo> IsDeleteFindList(Integer pageNum, Integer pageSize, ResourceInfoVO resourceInfoVO) {
        //获取当前登录用户对象
//        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();

        ResourceInfo resourceInfo = new ResourceInfo();
        BeanUtils.copyProperties(resourceInfoVO, resourceInfo);
//        if (activeUser.getUser().getType() ==2) {
//            resourceInfo.setUserId(activeUser.getUser().getUserId());
//        }else {
//            resourceInfo.setIds(DepUtils.getDepartmentAndChildrenIds(departmentMapper.selectAll(), activeUser.getUser().getDeptId()));
//        }
        PageHelper.startPage(pageNum, pageSize);
        List<ResourceInfo> resourceInfoList = resourceInfoMapper.selectResourceInfoListByIsDelete(resourceInfo);
        PageInfo<ResourceInfo> pageInfo = new PageInfo<>(resourceInfoList);
        return new PageVO<>(pageInfo.getTotal(), resourceInfoList);
    }

    /**
     * 清空资源回收站
     */
    @Override
    public void deleteResourceInfo(ResourceInfoVO resourceInfoVO) {
        //获得到登录后的用户信息，通用方式
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        ResourceInfo resourceInfo = new ResourceInfo();
        BeanUtils.copyProperties(resourceInfoVO, resourceInfo);
        if (activeUser.getUser().getType() ==2) {
            resourceInfo.setUserId(activeUser.getUser().getUserId());
        }else {
            resourceInfo.setIds(DepUtils.getDepartmentAndChildrenIds(departmentMapper.selectAll(), activeUser.getUser().getDeptId()));
        }
        List<Long> list = resourceInfoMapper.selectResourceInfoId(resourceInfo);
        //删除客户的跟进信息
        resourceInfoMapper.deleteCustomerFollowByIds(list);
        resourceInfoMapper.deleteResourceInfosByIds(list);
    }

    /**
     * 通过条件查出已删除的资源数据,用于导出
     *
     * @return
     */
    @Override
    public List<ResourceInfo> findByResourceInfoAll(ResourceInfoVO resourceInfoVO) {
        //获取当前登录用户对象
//        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        ResourceInfo resourceInfo = new ResourceInfo();
        BeanUtils.copyProperties(resourceInfoVO, resourceInfo);
//        if (activeUser.getUser().getType() ==2) {
//            resourceInfo.setUserId(activeUser.getUser().getUserId());
//        }else {
//            resourceInfo.setIds(DepUtils.getDepartmentAndChildrenIds(departmentMapper.selectAll(), activeUser.getUser().getDeptId()));
//        }
        return resourceInfoMapper.selectResourceInfoListByIsDelete(resourceInfo);
    }


    /**
     * 客户回收站
     *
     * @param pageNum        页码
     * @param pageSize       一页显示数据
     * @param resourceInfoVO 对象
     * @return
     */
    @Override
    public PageVO<ResourceInfo> selectAllCustomer(Integer pageNum, Integer pageSize, ResourceInfoVO resourceInfoVO) {
        //获取当前登录用户对象
//        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        ResourceInfo resourceInfo = new ResourceInfo();
        BeanUtils.copyProperties(resourceInfoVO, resourceInfo);
//        if (activeUser.getUser().getType() ==2) {
//            resourceInfo.setUserId(activeUser.getUser().getUserId());
//        }else {
//            resourceInfo.setIds(DepUtils.getDepartmentAndChildrenIds(departmentMapper.selectAll(), activeUser.getUser().getDeptId()));
//        }
        PageHelper.startPage(pageNum, pageSize);
        List<ResourceInfo> resourceInfoList = resourceInfoMapper.selectAllCustomer(resourceInfo);
        PageInfo<ResourceInfo> pageInfo = new PageInfo<>(resourceInfoList);
        return new PageVO<>(pageInfo.getTotal(), resourceInfoList);
    }

    /**
     * 清空或按添加清空回收站的客户和资源
     *
     * @param resourceInfoVO 对象
     */
    @Override
    public void deleteCustomer(ResourceInfoVO resourceInfoVO) {
        //获得到登录后的用户信息，通用方式
//        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        ResourceInfo resourceInfo = new ResourceInfo();
        BeanUtils.copyProperties(resourceInfoVO, resourceInfo);
//        if (activeUser.getUser().getType() ==2) {
//            resourceInfo.setUserId(activeUser.getUser().getUserId());
//        }else {
//            resourceInfo.setIds(DepUtils.getDepartmentAndChildrenIds(departmentMapper.selectAll(), activeUser.getUser().getDeptId()));
//        }
        List<Long> list = resourceInfoMapper.selectCustomerId(resourceInfo);
        //删除客户的跟进信息
        resourceInfoMapper.deleteCustomerFollowByIds(list);
        resourceInfoMapper.deleteResourceInfosByIds(list);
    }

    /**
     * 删除或批量回收站的客户和资源
     *
     * @param idList 客户id集合
     */
    @Override
    public void deleteCustomerId(List<Long> idList) {
        //删除客户的跟进信息
        resourceInfoMapper.deleteCustomerFollowByIds(idList);
        resourceInfoMapper.deleteResourceInfosByIds(idList);
    }

    /**
     * 批量分配或分配回收站的客户
     *
     * @param userList     用户id
     * @param resourceList 客户id
     * @return
     */
    @Override
    public int distributeCustomer(List<Long> userList, List<Long> resourceList) {
        //删除客户的跟进信息
        resourceInfoMapper.deleteCustomerFollowByIds(resourceList);
        int userSize = userList.size();
        int resourceSize = resourceList.size();
        int userIdS = 0;//用户的id下标
        int allocatedCount = 0; // 记录已分配的资源数量
        while (allocatedCount < resourceSize) {
            if (userSize == userIdS) {
                userIdS = 0;
            }
            // 更新已分配的资源数量
            allocatedCount += resourceInfoMapper.distributeCustomer(userList.get(userIdS), resourceList.get(allocatedCount));
            userIdS++;
        }
        return allocatedCount;
    }

    /**
     * 恢复客户
     *
     * @param resourceIds 客户id集合
     */
    @Override
    public void updateIsDelete(List<Long> resourceIds) {
        resourceInfoMapper.updateIsDelete(resourceIds);
    }


    /**
     * 公海预警
     *
     * @param pageNum        页码
     * @param pageSize       一页显示数据
     * @param resourceInfoVO 对象
     * @return
     */
    @Override
    public PageVO<ResourceInfo> selectHighSeasClient(Integer pageNum, Integer pageSize, ResourceInfoVO resourceInfoVO) {
        //获取当前登录用户对象
//        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        //获取当前用户的系统信息
        List<SysInformation> sysInformation = sysInformationMapper.getSysInformationByAccountName(Collections.singletonList(resourceInfoVO.getAccountName()));
//        if (activeUser.getUser().getType() ==2) {
//            resourceInfo.setUserId(activeUser.getUser().getUserId());
//        }else {
//            resourceInfo.setIds(DepUtils.getDepartmentAndChildrenIds(departmentMapper.selectAll(), activeUser.getUser().getDeptId()));
//        }
        ResourceInfo resourceInfo = new ResourceInfo();
        BeanUtils.copyProperties(resourceInfoVO, resourceInfo);
        PageHelper.startPage(pageNum, pageSize);
        if (sysInformation.get(0).getHighSeasTime() != null && sysInformation.get(0).getHighSeasTime() > 0) {
            if (sysInformation.get(0).getIsEnabledToHighSeas() == 1) {//判断是否开启自动转移公海
                resourceInfo.setHighSeasTime(sysInformation.get(0).getHighSeasTime() - 3);
            } else {
                return new PageVO<>(0, null);//默认公海预警
            }
        } else {
            //resourceInfo.setHighSeasTime(15 - 3);//默认转入公海
            return new PageVO<>(0, null);//默认公海预警
        }
        List<ResourceInfo> resourceInfoList = resourceInfoMapper.selectHighSeasClient(resourceInfo);
        PageInfo<ResourceInfo> pageInfo = new PageInfo<>(resourceInfoList);
        return new PageVO<>(pageInfo.getTotal(), resourceInfoList);
    }

    /**
     * 回收站预警
     *
     * @param pageNum        页码
     * @param pageSize       一页显示数据
     * @param resourceInfoVO 对象
     * @return
     */
    @Override
    public PageVO<ResourceInfo> selectRecycle(Integer pageNum, Integer pageSize, ResourceInfoVO resourceInfoVO) {
        //获取当前登录用户对象
//        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();

        //获取当前用户的系统信息
        List<SysInformation> sysInformation = sysInformationMapper.getSysInformationByAccountName(Collections.singletonList(resourceInfoVO.getAccountName()));
//        if (activeUser.getUser().getType() ==2) {
//            resourceInfo.setUserId(activeUser.getUser().getUserId());
//        }else {
//            resourceInfo.setIds(DepUtils.getDepartmentAndChildrenIds(departmentMapper.selectAll(), activeUser.getUser().getDeptId()));
//        }
        ResourceInfo resourceInfo = new ResourceInfo();
        BeanUtils.copyProperties(resourceInfoVO, resourceInfo);
        PageHelper.startPage(pageNum, pageSize);
        if (!sysInformation.isEmpty() && sysInformation.get(0).getExpiryDay() != null && sysInformation.get(0).getExpiryDay() > 0) {
            resourceInfo.setExpiryDay(sysInformation.get(0).getExpiryDay() - 3);
        } else {
            return new PageVO<>(0, null);//默认清空回收站
        }
        List<ResourceInfo> resourceInfoList = resourceInfoMapper.selectRecycle(resourceInfo);
        PageInfo<ResourceInfo> pageInfo = new PageInfo<>(resourceInfoList);
        return new PageVO<>(pageInfo.getTotal(), resourceInfoList);
    }

    /**
     * 定时函数调用的方法
     *
     * @return
     */
    @Override
    public void scheduled() {
        //拿到所有账号名称并且状态为正常的
        List<String> accountNames = resourceInfoMapper.getAccountNames();
        //通过账号名称得到各个的系统信息
        List<SysInformation> sysInformations = sysInformationMapper.getSysInformationByAccountName(accountNames);
        // 遍历 账号名称 列表
        for (String accountName : accountNames) {
            // 查找对应的系统信息
            SysInformation sysInfo = null;
            for (SysInformation information : sysInformations) {
                if (information.getAccountName().equals(accountName)) {
                    sysInfo = information;
                    break;
                }
            }
            // 处理找到或未找到系统信息的情况
            if (sysInfo != null) {
                //判断是否开启自动转移公海
                if (sysInfo.getIsEnabledToHighSeas() == 0) {
                    //判断转公海的时间是否有
                    if (sysInfo.getHighSeasTime() != null && sysInfo.getHighSeasTime() > 0) {
                        //查询出到达转公海的id
                        List<Long> resourceInfoIds = resourceInfoMapper.getHighSeasClientIdList(sysInfo.getHighSeasTime(),accountName);
                        if (resourceInfoIds != null && !resourceInfoIds.isEmpty()) {
                            //将查询出的id转公海
                            Integer count = resourceInfoMapper.insertHigh_seas_clientLists(resourceInfoIds);
                            System.out.println("转入公海的数量：" + count);
                        }
                    } else {
                        //查询出到达转公海的id
                        List<Long> resourceInfoIds = resourceInfoMapper.getHighSeasClientIdList(15,accountName);//默认转公海时间
                        if (resourceInfoIds != null && !resourceInfoIds.isEmpty()) {
                            //将查询出的id转公海
                            Integer count = resourceInfoMapper.insertHigh_seas_clientLists(resourceInfoIds);
                            System.out.println("转入公海的数量：" + count);
                        }
                    }
                }
                //判断清空回收站的时间是否有
                if (sysInfo.getExpiryDay() != null && sysInfo.getExpiryDay() > 0) {
                    //查询出到达清空回收站时间的id
                    List<Long> resourceInfoIds = resourceInfoMapper.getRecycleIdList(sysInfo.getExpiryDay(),accountName);
                    if (resourceInfoIds != null && !resourceInfoIds.isEmpty()) {
                        //将查询出的id删除
                        Integer count = resourceInfoMapper.deleteResourceInfosByIds(resourceInfoIds);
                        //删除客户的跟进信息
                        resourceInfoMapper.deleteCustomerFollowByIds(resourceInfoIds);
                        System.out.println("清空回收站的数量：" + count);
                    }
                } else {
                    //查询出到达清空回收站时间的id
                    List<Long> resourceInfoIds = resourceInfoMapper.getRecycleIdList(30,accountName);//默认清空回收站
                    if (resourceInfoIds != null && !resourceInfoIds.isEmpty()) {
                        //将查询出的id删除
                        Integer count = resourceInfoMapper.deleteResourceInfosByIds(resourceInfoIds);
                        //删除客户的跟进信息
                        resourceInfoMapper.deleteCustomerFollowByIds(resourceInfoIds);
                        System.out.println("清空回收站的数量：" + count);
                    }
                }
            } else {
                //查询出到达清空回收站时间的id
                List<Long> resourceInfoIds2 = resourceInfoMapper.getRecycleIdList(30,accountName);//默认清空回收站
                if (resourceInfoIds2 != null && !resourceInfoIds2.isEmpty()) {
                    //将查询出的id删除
                    Integer count2 = resourceInfoMapper.deleteResourceInfosByIds(resourceInfoIds2);
                    //删除客户的跟进信息
                    resourceInfoMapper.deleteCustomerFollowByIds(resourceInfoIds2);
                    System.out.println("清空回收站的数量：" + count2);
                }
            }
        }
    }

    /**
     * 删除归属人状态为-2的资源
     */
    @Override
    public void deleteByUserStatus() {

    }
}


